import { ref } from 'vue'
import type { TestResult } from '../types/speedTest'
import { realSpeedTestApi } from '../services/realSpeedTestApi'
import axios from 'axios'

export const useSpeedTest = () => {
  /* ---------- 状态 ---------- */
  const isTestingDownload = ref(false)
  const isTestingUpload   = ref(false)
  const isTestingPing     = ref(false)
  const errorMessage      = ref('')

  const downloadSpeed = ref(0)   // 平均下载
  const uploadSpeed   = ref(0)   // 平均上传
  const ping          = ref(0)   // 平均延迟
  const jitter        = ref(0)

  /* 🔥 新增：瞬时速度（仪表盘实时指针） */
  const instantSpeed  = ref(0)   // 下载/上传/ ping 的瞬时速度
  const instantUploadSpeed = ref(0)
  const instantPing   = ref(0)

  const progress      = ref(0)
  const testResults   = ref<TestResult[]>([])

  /* ---------- 网络连接检查 ---------- */
  const checkNetworkConnection = async (): Promise<boolean> => {
    if (!navigator.onLine) {
      return false
    }

    // 尝试多个国内可靠资源作为备选检查点
    const checkPoints = [
      'https://www.baidu.com/favicon.ico',
      'https://cdn.jsdelivr.net/npm/vue@3/favicon.ico',
      'https://cdn.bootcdn.net/ajax/libs/axios/1.6.0/axios.min.js'
    ]

    // 尝试检查点
    for (const url of checkPoints) {
      try {
        await axios.head(url, { timeout: 3000 })
        return true
      } catch {
        // 继续尝试下一个检查点
      }
    }

    // 如果所有外部检查都失败，尝试访问本地API端点
    try {
      await axios.head('/api/health', { timeout: 2000 })
      return true
    } catch {
      // 本地API也不可用，返回true让测试流程继续，实际API调用失败时会显示具体错误
      console.warn('无法验证网络连接，继续测速流程')
      return true
    }
  }

  /* ---------- 主流程 ---------- */
  const startSpeedTest = async () => {
    // 重置状态
    errorMessage.value = ''
    downloadSpeed.value = uploadSpeed.value = ping.value = jitter.value = 0
    instantSpeed.value  = instantUploadSpeed.value = instantPing.value = 0
    progress.value      = 0

    // 检查网络连接
    const isConnected = await checkNetworkConnection()
    if (!isConnected) {
      errorMessage.value = '网络连接不可用，请检查网络设置'
      return
    }

    try {
      /* 1. Ping */
      isTestingPing.value = true
      progress.value = 0
      // 为ping测试添加定期进度更新
      const pingProgressInterval = setInterval(() => {
        if (progress.value < 20 && isTestingPing.value) {
          progress.value += 1
        }
      }, 200)
      
      const pingRes = await realSpeedTestApi.testPing(p => { 
        instantPing.value = p 
      }) // 实时回调
      
      clearInterval(pingProgressInterval)
      ping.value = pingRes.ping
      jitter.value = pingRes.jitter
      progress.value = 20
      isTestingPing.value = false

      /* 2. 下载 */
      isTestingDownload.value = true
      // 下载开始时间，用于计算进度
      const downloadStartTime = Date.now()
      const downloadTestDuration = 15000 // 预计15秒下载测试
      
      const downRes = await realSpeedTestApi.testDownloadSpeed(speed => {
        instantSpeed.value = speed         // 实时速度
        downloadSpeed.value = speed        // 同时更新平均
        
        // 结合时间和速度来计算进度，确保进度平滑更新
        const elapsedTime = Date.now() - downloadStartTime
        const timeProgress = Math.min((elapsedTime / downloadTestDuration) * 50, 50)
        const speedProgress = Math.min((speed / 1000) * 25, 25) // 速度贡献更小比例
        const combinedProgress = timeProgress + speedProgress
        
        progress.value = 20 + combinedProgress
      })
      
      downloadSpeed.value = downRes
      progress.value = 70
      isTestingDownload.value = false

      /* 3. 上传 */
      isTestingUpload.value = true
      // 上传开始时间，用于计算进度
      const uploadStartTime = Date.now()
      const uploadTestDuration = 12000 // 预计12秒上传测试
      
      const upRes = await realSpeedTestApi.testUploadSpeed(speed => {
        instantUploadSpeed.value = speed
        uploadSpeed.value = speed
        
        // 结合时间和速度来计算进度，确保进度平滑更新
        const elapsedTime = Date.now() - uploadStartTime
        const timeProgress = Math.min((elapsedTime / uploadTestDuration) * 30, 30)
        const speedProgress = Math.min((speed / 500) * 15, 15) // 速度贡献更小比例
        const combinedProgress = timeProgress + speedProgress
        
        progress.value = 70 + combinedProgress
      })
      
      uploadSpeed.value = upRes
      progress.value = 100
      isTestingUpload.value = false

      /* 4. 保存结果 */
      testResults.value.unshift({
        timestamp: Date.now(),
        download: downloadSpeed.value,
        upload:   uploadSpeed.value,
        ping:     ping.value,
        jitter:   jitter.value
      })

      setTimeout(() => (progress.value = 0), 3000)
    } catch (e) {
      console.error('网速测试失败:', e)
      errorMessage.value = `测试失败: ${e.message || '网络连接问题'}`
    } finally {
      isTestingDownload.value = isTestingUpload.value = isTestingPing.value = false
      progress.value = 0
    }
  }

  /* ---------- 供模板使用 ---------- */
  return {
    isTestingDownload,
    isTestingUpload,
    isTestingPing,
    downloadSpeed,
    uploadSpeed,
    ping,
    jitter,
    progress,
    testResults,
    errorMessage,
    startSpeedTest,

    /* 实时指针用 */
    instantSpeed,
    instantUploadSpeed,
    instantPing
  }
}